package cn.sxt.service;

import cn.sxt.mapper.UserMapper;
import cn.sxt.pojo.Role;
import cn.sxt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service  //service需要执行登录的逻辑操作,所以需要实现一个UserDetailsService接口
public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override //loadUserByUsername表示根据用户名查询用户
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {  //如果用户查找不到
            throw new UsernameNotFoundException("用户不存在!");
        }
        //getUserRolesById表示根据用户id查询用户的角色的集合
        List<Role> roles = userMapper.getUserRolesById(user.getId());
        user.setRoles(roles);
        return user;
    }

}
